package com.lh.user.service.impl;

import com.lh.common.utils.CodecUtils;
import com.lh.common.utils.DateUtils;
import com.lh.common.utils.NumberUtils;
import com.lh.user.enumm.DataTypeEnum;
import com.lh.user.mapper.UserMapper;
import com.lh.user.pojo.UserDo;
import com.lh.user.service.IUserService;
import com.netflix.discovery.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author liuhe
 * @date 2020/07/02
 */
@Service
@Slf4j
public class UserServiceImpl implements IUserService {

    private final UserMapper userMapper;
    private final RabbitTemplate rabbitTemplate;
    private final StringRedisTemplate stringRedisTemplate;

    static final String KEY_PREFIX = "user:code:phone:";
    static final String KEY_PREFIX_COUNT = "user:code:count:";

    public UserServiceImpl(UserMapper userMapper, RabbitTemplate rabbitTemplate, RedisTemplate redisTemplate, StringRedisTemplate stringRedisTemplate) {
        this.userMapper = userMapper;
        this.rabbitTemplate = rabbitTemplate;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public Boolean checkParams(Integer type, String value) {
        DataTypeEnum dataType = DataTypeEnum.of(type);
        UserDo userDo = new UserDo();
        switch (dataType) {
            case USERNAME:
                userDo.setUsername(value);
                break;
            case PHONE:
                userDo.setPhone(value);
                break;
            default:
                return null;
        }
        return this.userMapper.selectCount(userDo) == 0;
    }

    /**
     * 发送手机验证码考虑问题
     * 1、验证码过期时间，比如设置5分钟
     * 2、获取验证码次数限制，比如设置每天10次。
     *
     * @param phone
     * @return
     */
    @Override
    public Boolean sendSmsCode(String phone) {
        if (StringUtils.isEmpty(phone)) {
            return false;
        }
        //1、判断验证码是否需要重新生成
        String code = this.stringRedisTemplate.opsForValue().get(KEY_PREFIX + phone);
        if (!StringUtils.isEmpty(code)) {
            return true;
        }
        //2、判断今天验证码是否发送超过10次
        String sendCount = this.stringRedisTemplate.opsForValue().get(KEY_PREFIX_COUNT + phone);
        if (!StringUtils.isEmpty(sendCount) && Integer.parseInt(sendCount) > 10) {
            return false;
        }
        if (StringUtils.isEmpty(sendCount)) {
            sendCount = "0";
        } else {
            int sendCountTmp = Integer.parseInt(sendCount);
            sendCountTmp++;
            sendCount = String.valueOf(sendCountTmp);
        }
        this.stringRedisTemplate.opsForValue().set(KEY_PREFIX_COUNT + phone, sendCount, DateUtils.getNowToZeroMills(), TimeUnit.SECONDS);

        // 3、生成随机码并通过mq发送
        code = NumberUtils.generateCode(6);
        HashMap<String, String> msg = new HashMap<>();
        msg.put("phone", phone);
        msg.put("code", code);
        this.stringRedisTemplate.opsForValue().set(KEY_PREFIX + phone, code, 5, TimeUnit.MINUTES);
        try {
            this.rabbitTemplate.convertAndSend("leyou.sms.exchange", "sms.verify.code", msg);
            return true;
        } catch (Throwable e) {
            log.error("发送短信失败：phone:{},code:{}", phone, code);
            return false;
        }
    }

    /**
     * - 1）校验短信验证码
     * - 2）生成盐
     * - 3）对密码加密
     * - 4）写入数据库
     * - 5）删除Redis中的验证码
     */
    @Override
    public Boolean register(UserDo user, String code) {
        if (StringUtils.isEmpty(code)) {
            return false;
        }
        // 1、校验验证码
        String codeFromRedis = this.stringRedisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone());
        if (!org.apache.commons.lang.StringUtils.equals(code, codeFromRedis)) {
            return false;
        }
        // 2、生成盐值
        String salt = CodecUtils.generateSalt();
        user.setSalt(salt);

        // 3、密码加密
        user.setPassword(CodecUtils.md5Hex(user.getPassword(), salt));

        // 4、添加进数据库
        user.setId(null);
        user.setCreated(new Date());

        boolean insert = this.userMapper.insertSelective(user) == 1;
        if (insert) {
            this.stringRedisTemplate.delete(KEY_PREFIX + user.getPhone());
        }
        return insert;
    }

    @Override
    public UserDo queryUser(String username, String password) {
        // 查询
        UserDo record = new UserDo();
        record.setUsername(username);
        UserDo user = this.userMapper.selectOne(record);
        // 校验用户名
        if (user == null) {
            return null;
        }
        // 校验密码
        if (!user.getPassword().equals(CodecUtils.md5Hex(password, user.getSalt()))) {
            return null;
        }
        // 用户名密码都正确
        return user;
    }
}
